from django import forms
from django.core.exceptions import ValidationError
from web.forms.bootstrap import BootStrapForm
from web.forms.widgets import ColorRadioSelect
from web import models

class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    # desc = forms.CharField(widget=forms.Textarea(attrs={'xx': 123}))
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            # 'desc': forms.Textarea(attrs={'xx': 123})
            # 不加括号源码中会自动帮我们加上
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    def clean_name(self):
        ''' 项目校验 '''
        # 当前用户的项目名不能重复
        name = self.cleaned_data['name']
        is_exist = models.Project.objects.filter(name=name, creator=self.request.saas.user).exists()
        if is_exist:
            raise ValidationError("项目名已存在")

        # 当前用户是否还有额度创建项目
        # 最多创建的项目个数
        most_count = self.request.saas.price_policy.project_num
        # 已经创建的项目
        count = models.Project.objects.filter(creator=self.request.saas.user).count()

        if count >= most_count:
            raise ValidationError("项目个数超限，如需继续请购买套餐")

        return name